require 'digest/sha1'

class User < ActiveRecord::Base
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
  validates_presence_of :email
  validates_uniqueness_of :email
  attr_accessor :password_confirmation
  validates_confirmation_of :password
  validate :password_non_blank
  def self.authenticate(email, password)
    user = self.find_by_email(email)
    if user
      expected_password = encrypted_password(password, user.password_salt)
      if user.password_hash != expected_password
        user = nil
      end
    end
    user
  end
  # 'password' is a virtual attribute
  def password
    @password
  end
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_password_salt
    self.password_hash = User.encrypted_password(self.password, self.password_salt)
  end
  private
  def password_non_blank
    errors.add_to_base("Missing password" ) if password_hash.blank?
  end
  def create_new_password_salt
    self.password_salt = self.object_id.to_s + rand.to_s
  end
  def self.encrypted_password(password, password_salt)
    string_to_hash = password + "wibble" + password_salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def self.search(search, page)
    unless search
      User.paginate :per_page => 10, :page => page
    else
      User.paginate :per_page => 10, :page => page,
      :conditions => ['users.first_name like ? or users.last_name like ?', "%#{search}%", "%#{search}%"]
    end
  end
end